import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerTemplate')
export class PlayerTemplate extends Component {
    @property("number")
    score: number = 0;
    serverUrl: string = 'ws://127.0.0.1:7890';
    socket: WebSocket;
    playerId: string;
    @property("String")
    username: string = "";
    start() {

    }

    update(deltaTime: number) {

    }
    connectToServer() {
        this.socket = new WebSocket(this.serverUrl);

        this.socket.onopen = () => {

            // 发送玩家连接请求或其他初始化数据
            this.socket.send(JSON.stringify({ type: 'join', playerId: this.playerId }));
        };

        this.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            // 处理服务端返回的数据
            console.log('Received data:', data);
        };

        this.socket.onclose = () => {
            console.log('Connection closed');
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    }
}


